package com.xlh.wjdcserver.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.exception.QuestionnaireException;
import com.common.result.Result;
import com.property.dto.AnswerDTO;
import com.property.dto.AnswerExportDTO;
import com.property.dto.AnswerPageDTO;
import com.property.entity.Questionnaire;
import com.property.vo.AnswerPageVO;
import com.property.vo.AnswerVO;
import com.xlh.wjdcserver.mapper.QuestionnaireMapper;
import com.xlh.wjdcserver.service.AnswerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Tag(name = "答卷接口")
@RestController
@RequestMapping("/answer")
public class AnswerController {

    @Autowired
    private AnswerService answerService;

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Operation(summary = "添加答卷")
    @PostMapping("/addAnswer")
    public Result addAnswer(@RequestBody List<AnswerDTO> answerDTOs) {
        // 查询问卷是否过期
        Questionnaire questionnaire = questionnaireMapper.selectById(answerDTOs.get(0).getQid());
        if(questionnaire.getEndTime().isBefore(LocalDateTime.now()))
        {
            throw new QuestionnaireException("问卷已过期");

        }

        answerService.addAnswer(answerDTOs);

        return Result.ok();
    }

    @Operation(summary = "分页查询答卷")
    @GetMapping("/listAnswer")
    public Result<Page<AnswerVO>> listAnswer(AnswerPageDTO answerPageDTO)
    {
        return Result.ok(answerService.listAnswer(answerPageDTO));
    }

    @Operation(summary = "导出答卷")
    @GetMapping("/export")
    public Result<byte []> export(AnswerExportDTO answerExportDTO) throws IOException
    {
        // 调用服务层的导出功能，返回字节数组
        byte[] fileData = answerService.export(answerExportDTO);

        // 设置响应头，让浏览器知道这是一个文件下载请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDisposition(ContentDisposition.attachment().filename("答卷.xlsx").build());

        // 返回文件字节数据
        return Result.ok(fileData);
    }

}
